/*
	模板发送邮件

	table.exportFile(id, data, type); //导出数据
	table.checkStatus('ID') 该方法可获取到表格所有的选中行相关数据 
*/

var adminLoginedInfo = Cookies.getJSON('kplus_ad_logined_info');
var SYS_TEM_MAIL_ID = ['kpMail201803280101', 'kpMail201803280112', 'kpMail201803280113', 'kpMail201803280114', 'kpMail201803280115']
var EMAIL_DATA = {}
var SELECT_SEND_USER_DATA = []
var STATUS = {"0": "封禁", "1": "正常"}
var OPTIONS_MODEL_ID = null;

function DomInit(){

	var ajaxData = { aId: adminLoginedInfo.aId, aToken: adminLoginedInfo.aToken };

	var WEditor = window.wangEditor, editorHtml = new WEditor('#html');
	editorHtml.create();

	var initForm = function(data, form){

		var select = $('select[name="model_name"]');
		data.map(function(item, index){
			if ($.inArray(item.model_id, SYS_TEM_MAIL_ID) === -1){
				var option = '<option value="'+ item.model_id +'">'+ item.name +'</option>';
				select.append(option)
				EMAIL_DATA[item.model_id] = item;
			}
		})
		form.render();
	}

	this.getEmailModel = function(layer, form){
		/*
			@获取模板列表
		*/
		var loadIndex = layer.load(1, { shade: [0.5, '#000'] });
		var _ajaxData = ajaxData;

		$.ajax({
			url: BASE_SERVICEURL + URlS.sys_email,
			type: 'GET',
			data: _ajaxData,
			success: function(responseData){
				layer.close(loadIndex);
				if(responseData.msg.code == 200){
					//console.log(responseData.data)
					//initTable(responseData.data, form)
					initForm(responseData.data, form);
				}else{
					layer.msg(responseData.msg.msg, {time: 2000})
				}
			},
			error: function(responseData){
				layer.close(loadIndex);
				layer.msg(MESSAGES.service_error, {time: 2000});
			}
		});
	};

	this.enterModelShow = function(model_id, form){
		var model_data = EMAIL_DATA[model_id];

		var form_data = {
			title: model_data.subject,
		}
		OPTIONS_MODEL_ID = model_id;
		editorHtml.txt.html(model_data.html);

		form.val('email-detail-from', form_data)
		form.render();
	}

	var initTable = function(data, table){
		var table_data = []
		data.map(function(item, index){
			table_data.push({
				uId: item.u_id,
				uName: item.u_name,
				uLevel: item.vip_level,
				uMail: item.u_mail,
				uStatus: STATUS[item.u_status],
				uPhone: item.u_phone,
			})
		})

		table.render({
			elem: '#tableContent',
			limit: 30, //分页
			/*height: 360,*/
			page: true,
			cols:[[ //表头
				{type:'checkbox', width: 60, title: '选择'},
				{field: 'uId', title: '会员ID', sort: true, width: 160},
				{field: 'uName', title: '会员名', sort: true, width: 120},
				{field: 'uMail', title: '会员邮箱', sort: true, width: 120},
				{field: 'uPhone', title: '会员手机', sort: true, width:200},
				{field: 'uLevel', title: '会员等级', sort: true, width: 200},
				{field: 'uStatus', title: '会员状态', sort: true, width: 120},
			]],
			data:table_data
		});
	}

	var createUserList = function(data, table){
		
		initTable(data, table)
		var content = $('#userListTable');
		layer.open({
			type: 1,
			closeBtn: 0, 
			anim: 2,
			shadeClose: true,
			area: ['60%', '660px'],
			content: content
		})
	}

	this.getCanSendUser = function(table){
		/*
			@获取可发送信息会员
		*/
		var loadIndex = layer.load(1, { shade: [0.5, '#000'] });
		var _ajaxData = $.extend(ajaxData, {status: '1'});

		$.ajax({
			url: BASE_SERVICEURL + URlS.au,
			type: 'GET',
			data: _ajaxData,
			success: function(responseData){
				
				if(responseData.msg.code == 200){
					console.log(responseData);
					
					createUserList(responseData.data.data, table)
					layer.close(loadIndex);
				}else{
					layer.close(loadIndex);
					layer.msg(MESSAGES.get_form_error + responseData.msg.msg, {time: 2000});
				}
			},
			error: function(responseData){
				layer.msg(MESSAGES.service_error, {time: 2000, end:function(){
					//导向500页面
					location.href = './500.html';
				}});
			}
		});
	};

	var showSendRes = function(data){
		var list = ''
		data.map(function(item, index){
			if(item.result.code === 200){
				list += '<li><span>'+ item.userName +'</span><span class="send-res-success">SUCCESS</span></li>';
			}else{
				list += '<li><span>'+ item.userName +'</span><span class="send-res-error">FAIL</span></li>'
			}
		})

		layer.open({
			type: 1,
			closeBtn: 0, 
			anim: 2,
			shadeClose: true,
			area: ['420px', '460px'],
			content: '<ul class="send-res">'+ list +'</ul>'
		})

	}

	this.sendEmail = function(data){
		/*
			@发送邮件
		*/
		var loadIndex = layer.load(1, { shade: [0.5, '#000'] });
		var _ajaxData = $.extend(ajaxData, data);
		console.log(_ajaxData)
		$.ajax({
			url: BASE_SERVICEURL + URlS.sys_email,
			type: 'POST',
			data: _ajaxData,
			success: function(responseData){
				
				if(responseData.msg.code == 200){
					console.log(responseData);
					showSendRes(responseData.data)
					layer.close(loadIndex);
				}else{
					layer.close(loadIndex);
					layer.msg(MESSAGES.get_form_error + responseData.msg.msg, {time: 2000});
				}
			},
			error: function(responseData){
				layer.msg(MESSAGES.service_error, {time: 2000, end:function(){
					//导向500页面
					location.href = './500.html';
				}});
			}
		});

	}
}

$(function(){
	layui.use(['layer', 'form', 'table'], function(){
		var layer = layui.layer, form = layui.form, table = layui.table;
		dom_init = new DomInit();
		dom_init.getEmailModel(layer, form, table)

		// 点选发送会员
		form.on('submit(selectSendUser)', function(data){

			dom_init.getCanSendUser(table);
			return false;
		})
		//应用模板
		form.on('submit(enterModel)', function(data){
			//console.log(data)
			var f = data.field;
			dom_init.enterModelShow(f.model_name, form);
			return false;
		})
		//确认选中
		form.on('submit(select)', function(){
			var data = table.checkStatus('tableContent');
			//选中添加
			var users_email_str = "";
			data.data.map(function(item, index){
				//console.log(item)
				users_email_str += item.uMail + ';';
				SELECT_SEND_USER_DATA.push(item);
				layer.closeAll();
			})
			$('input[name="sendTo"]').val(users_email_str);
			return false;
		})
		// 确认发送邮件
		form.on('submit(sendEmail)', function(){
			var array = []
			SELECT_SEND_USER_DATA.map(function(item, index){
				array.push(item.uId)
			})
			var sendData = {
				wId: OPTIONS_MODEL_ID,
				sign: 'm',  // 模板发送 请固定填入 m
				spmId: array.join(';')
			}
			dom_init.sendEmail(sendData);
			return false;
		})
	})
})

